// 文档合并页面的主要JavaScript代码
document.addEventListener('DOMContentLoaded', function() {
    // 初始化变量
    let examFile = null;
    let answerFile = null;
    let currentTaskId = null;
    
    // 获取DOM元素
    const examDropZone = document.getElementById('examDropZone');
    const answerDropZone = document.getElementById('answerDropZone');
    const examFileInput = document.getElementById('examFileInput');
    const answerFileInput = document.getElementById('answerFileInput');
    const examFileList = document.getElementById('examFileList');
    const answerFileList = document.getElementById('answerFileList');
    const mergeButton = document.getElementById('mergeButton');
    const progressArea = document.getElementById('progressArea');
    const progressBar = document.getElementById('progressBar');
    const progressText = document.getElementById('progressText');
    const resultArea = document.getElementById('resultArea');
    const downloadButton = document.getElementById('downloadBtn');
    const errorModal = document.getElementById('errorModal');
    const errorMessage = document.getElementById('errorMessage');
    const closeErrorModal = document.getElementById('closeErrorModal');
    const loadingOverlay = document.getElementById('loadingOverlay');
    
    // 设置拖放区域
    if (examDropZone && examFileInput) {
        setupDropZone(examDropZone, examFileInput, 'exam');
    }
    
    if (answerDropZone && answerFileInput) {
        setupDropZone(answerDropZone, answerFileInput, 'answer');
    }
    
    // 设置文件输入监听
    if (examFileInput) {
        examFileInput.addEventListener('change', (e) => handleFileSelect(e, 'exam'));
    }
    
    if (answerFileInput) {
        answerFileInput.addEventListener('change', (e) => handleFileSelect(e, 'answer'));
    }
    
    // 设置合并按钮
    if (mergeButton) {
        mergeButton.addEventListener('click', startMerge);
    }
    
    // 设置下载按钮
    if (downloadButton) {
        downloadButton.addEventListener('click', downloadMergedDocument);
    }
    
    // 设置错误模态框关闭按钮
    if (closeErrorModal) {
        closeErrorModal.addEventListener('click', () => {
            errorModal.classList.add('hidden');
        });
    }
    
    // 确保关闭按钮可以点击 - 修复事件委托问题
    document.addEventListener('click', (e) => {
        // 处理错误模态框关闭按钮
        if (e.target.id === 'closeErrorModal' || (e.target.closest && e.target.closest('#closeErrorModal'))) {
            if (errorModal) {
                errorModal.classList.add('hidden');
            }
        }
        
        // 处理服务繁忙提示框关闭按钮
        if (e.target.id === 'closeBusyMessageBtn' || (e.target.closest && e.target.closest('#closeBusyMessageBtn'))) {
            if (resultArea) {
                resultArea.classList.add('hidden');
            }
        }
        
        // 处理下载错误提示框关闭按钮
        if (e.target.id === 'closeDownloadErrorBtn' || (e.target.closest && e.target.closest('#closeDownloadErrorBtn'))) {
            if (resultArea) {
                resultArea.classList.add('hidden');
            }
        }
    });
    
    /**
     * 设置拖放区域
     */
    function setupDropZone(dropZone, fileInput, type) {
        ['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
            dropZone.addEventListener(eventName, preventDefaults, false);
        });
        
        function preventDefaults(e) {
            e.preventDefault();
            e.stopPropagation();
        }
        
        ['dragenter', 'dragover'].forEach(eventName => {
            dropZone.addEventListener(eventName, () => {
                dropZone.classList.add('border-blue-500');
            });
        });
        
        ['dragleave', 'drop'].forEach(eventName => {
            dropZone.addEventListener(eventName, () => {
                dropZone.classList.remove('border-blue-500');
            });
        });
        
        dropZone.addEventListener('drop', (e) => {
            const files = e.dataTransfer.files;
            if (files.length > 0) {
                handleFiles(files, type);
            }
        });
        
        dropZone.addEventListener('click', () => {
            fileInput.click();
        });
    }
    
    /**
     * 处理文件选择
     */
    function handleFileSelect(event, type) {
        const files = event.target.files;
        if (files.length > 0) {
            handleFiles(files, type);
        }
    }
    
    /**
     * 处理文件
     */
    function handleFiles(files, type) {
        const file = files[0];
        
        // 验证文件类型
        const allowedTypes = ['.pdf', '.doc', '.docx'];
        const fileExtension = '.' + file.name.split('.').pop().toLowerCase();
        if (!allowedTypes.includes(fileExtension)) {
            showError('不支持的文件格式，请上传PDF或Word文档');
            return;
        }
        
        // 验证文件大小（20MB）
        if (file.size > 20 * 1024 * 1024) {
            showError('文件大小不能超过20MB');
            return;
        }
        
        // 更新文件变量
        if (type === 'exam') {
            examFile = file;
            updateFileList(examFileList, file, 'exam');
        } else {
            answerFile = file;
            updateFileList(answerFileList, file, 'answer');
        }
        
        // 更新合并按钮状态
        updateMergeButtonState();
    }
    
    /**
     * 更新文件列表显示
     */
    function updateFileList(container, file, type) {
        container.innerHTML = `
            <div class="flex items-center justify-between bg-gray-50 p-3 rounded-lg">
                <div class="flex items-center space-x-3">
                    <i class="fas ${getFileIcon(file.name)} text-gray-500"></i>
                    <div>
                        <p class="text-sm font-medium text-gray-700">${file.name}</p>
                        <p class="text-xs text-gray-500">${formatFileSize(file.size)}</p>
                    </div>
                </div>
                <button type="button" class="text-red-500 hover:text-red-700" onclick="removeFile('${type}')">
                    <i class="fas fa-times"></i>
                </button>
            </div>
        `;
    }
    
    /**
     * 更新合并按钮状态
     */
    function updateMergeButtonState() {
        mergeButton.disabled = !(examFile && answerFile);
    }
    
    /**
     * 开始合并
     */
    async function startMerge() {
        if (!examFile || !answerFile) {
            showError('请先上传试卷和答案文件');
            return;
        }
        
        try {
            // 隐藏结果区域
            resultArea.classList.add('hidden');
            
            // 显示浮动进度条
            const floatingProgress = document.getElementById('floatingProgress');
            if (floatingProgress) {
                console.log('显示浮动进度条 - startMerge内');
                floatingProgress.style.display = 'block';
                setTimeout(() => {
                    floatingProgress.classList.add('visible');
                }, 10);
            } else {
                console.error('未找到浮动进度条元素');
            }
            
            // 初始进度
            updateProgress(5);
            
            // 记录处理日志（虽然不可见，但后台仍会更新）
            addProcessLog('开始处理文档...');
            
            const formData = new FormData();
            
            // 获取合并顺序
            const mergeOrder = document.querySelector('input[name="mergeOrder"]:checked').value;
            
            // 根据合并顺序添加文件
            if (mergeOrder === 'question_first') {
                // 试卷在前，答案在后
                formData.append('answer_files', examFile);
                formData.append('paper_files', answerFile);
                addProcessLog('已选择合并顺序：试卷在前，答案在后');
            } else {
                // 答案在前，试卷在后
                formData.append('paper_files', examFile);
                formData.append('answer_files', answerFile);
                addProcessLog('已选择合并顺序：答案在前，试卷在后');
            }
            
            // 添加其他参数
            formData.append('merge_order', mergeOrder);
            formData.append('output_format', 'auto');
            
            addProcessLog(`正在上传文件：${examFile.name} 和 ${answerFile.name}`);
            
            try {
                const response = await Api.mergeDocuments(formData);
                currentTaskId = response.taskId;
                
                addProcessLog('文件上传成功，开始处理...');
                
                // 开始轮询任务状态
                await pollTaskStatus();
            } catch (error) {
                console.error('合并请求错误:', error);
                
                // 检查是否是服务繁忙状态 (503)
                if (error.status === 503 || (error.response && error.response.status === 503)) {
                    // 服务繁忙，显示友好提示
                    
                    // 创建自定义的服务繁忙提示
                    const busyMessage = error.message || '系统正在为其他用户处理合并请求，请稍后再试';
                    
                    // 显示友好的等待提示
                    resultArea.classList.remove('hidden');
                    resultArea.className = 'mt-4 p-4 bg-yellow-50 border border-yellow-200 rounded-lg';
                    resultArea.innerHTML = `
                        <div class="flex items-center justify-between mb-3">
                            <div class="flex items-center">
                                <div class="flex-shrink-0">
                                    <i class="fas fa-exclamation-circle text-yellow-500 text-2xl"></i>
                                </div>
                                <div class="ml-3">
                                    <h3 class="text-lg font-medium text-yellow-800">系统繁忙</h3>
                                    <p class="text-sm text-yellow-600">${busyMessage}</p>
                                </div>
                            </div>
                            <button type="button" id="closeBusyMessageBtn" class="text-gray-400 hover:text-gray-600 p-1">
                                <i class="fas fa-times"></i>
                            </button>
                        </div>
                        <div class="text-center">
                            <button type="button" id="retryButton" class="mt-2 px-4 py-2 bg-yellow-200 hover:bg-yellow-300 text-yellow-800 rounded-md text-sm font-medium transition duration-200">
                                稍后重试
                            </button>
                        </div>
                    `;
                    
                    // 添加关闭按钮的点击事件 - 使用setTimeout确保DOM已经渲染完成后再绑定事件
                    setTimeout(() => {
                        const closeBtn = document.getElementById('closeBusyMessageBtn');
                        if (closeBtn) {
                            closeBtn.onclick = function() {
                                resultArea.classList.add('hidden');
                            };
                        }
                        
                        // 添加重试按钮的点击事件
                        const retryBtn = document.getElementById('retryButton');
                        if (retryBtn) {
                            retryBtn.onclick = function() {
                                // 重置处理状态
                                resultArea.classList.add('hidden');
                                updateMergeButtonState();
                            };
                        }
                    }, 0);
                } else {
                    // 其他错误
                    showError(error.message || '合并请求失败');
                }
            }
        } catch (error) {
            console.error('合并请求失败:', error);
            showError(error.message);
        }
    }
    
    /**
     * 轮询任务状态
     */
    async function pollTaskStatus() {
        try {
            if (!currentTaskId || currentTaskId === 'null') {
                throw new Error('任务ID无效，请重新上传文件');
            }
            
            // 添加进度模拟
            let currentProgress = 5;
            let lastReportedProgress = 0;
            const progressInterval = setInterval(() => {
                // 模拟进度增加，最多到95%
                if (currentProgress < 95) {
                    // 根据当前进度决定增加速度
                    let increment = 0;
                    if (currentProgress < 30) {
                        // 文件上传阶段 - 快速增加
                        increment = 2;
                    } else if (currentProgress < 60) {
                        // 解析内容阶段 - 中速增加
                        increment = 1.5;
                    } else if (currentProgress < 80) {
                        // 合并文档阶段 - 慢速增加
                        increment = 1;
                    } else {
                        // 生成结果阶段 - 很慢增加
                        increment = 0.5;
                    }
                    currentProgress += increment;
                    
                    // 只有当进度有明显变化时才更新UI
                    const roundedProgress = Math.min(Math.round(currentProgress), 95);
                    if (roundedProgress > lastReportedProgress) {
                        updateProgress(roundedProgress);
                        lastReportedProgress = roundedProgress;
                    }
                }
            }, 500);
            
            try {
                const response = await Api.getTaskStatus(currentTaskId);
                
                // 清除进度模拟
                clearInterval(progressInterval);
                
                // 检查是否有错误状态
                if (response.status && response.status.toUpperCase() === 'ERROR') {
                    // 显示友好的错误消息
                    throw new Error(response.message || '获取任务状态失败');
                }
                
                if (response.status.toUpperCase() === 'COMPLETED') {
                    // 更新进度到100%
                    updateProgress(100);
                    // 显示下载提示
                    const statusElement = document.getElementById('progressStatus');
                    if (statusElement) {
                        statusElement.textContent = '处理完成，开始下载...';
                        statusElement.className = 'text-sm text-green-600 text-center font-medium';
                    }
                    // 自动触发下载
                    await downloadMergedDocument();
                    return;
                } else if (response.status.toUpperCase() === 'FAILED') {
                    throw new Error(response.message || '合并失败');
                }
                
                // 更新进度
                updateProgress(response.progress || 0);
                
                // 继续轮询
                setTimeout(pollTaskStatus, 1000);
            } catch (error) {
                // 清除进度模拟
                clearInterval(progressInterval);
                
                console.error('任务状态轮询失败:', error);
                
                // 检查错误消息是否包含特定文本
                const errorMsg = error.message || '获取任务状态失败';
                
                // 针对不同类型的错误显示不同的提示
                if (errorMsg.includes('后台处理服务暂时不可用') || 
                    errorMsg.includes('服务不可用') || 
                    error.status === 503) {
                    // 显示友好的服务不可用提示
                    
                    // 显示友好的等待提示
                    resultArea.classList.remove('hidden');
                    resultArea.className = 'mt-4 p-4 bg-yellow-50 border border-yellow-200 rounded-lg';
                    resultArea.innerHTML = `
                        <div class="flex items-center justify-between mb-3">
                            <div class="flex items-center">
                                <div class="flex-shrink-0">
                                    <i class="fas fa-exclamation-circle text-yellow-500 text-2xl"></i>
                                </div>
                                <div class="ml-3">
                                    <h3 class="text-lg font-medium text-yellow-800">处理服务暂时不可用</h3>
                                    <p class="text-sm text-yellow-600">${errorMsg}</p>
                                </div>
                            </div>
                            <button type="button" id="closeBusyMessageBtn" class="text-gray-400 hover:text-gray-600 p-1">
                                <i class="fas fa-times"></i>
                            </button>
                        </div>
                        <div class="text-center">
                            <button type="button" id="retryButton" class="mt-2 px-4 py-2 bg-yellow-200 hover:bg-yellow-300 text-yellow-800 rounded-md text-sm font-medium transition duration-200">
                                重新尝试
                            </button>
                        </div>
                    `;
                    
                    // 添加关闭按钮的点击事件 - 使用setTimeout确保DOM已经渲染完成后再绑定事件
                    setTimeout(() => {
                        const closeBtn = document.getElementById('closeBusyMessageBtn');
                        if (closeBtn) {
                            closeBtn.onclick = function() {
                                resultArea.classList.add('hidden');
                            };
                        }
                        
                        // 添加重试按钮的点击事件
                        const retryBtn = document.getElementById('retryButton');
                        if (retryBtn) {
                            retryBtn.onclick = function() {
                                // 重置处理状态
                                resultArea.classList.add('hidden');
                                // 重新启动合并过程
                                startMerge();
                            };
                        }
                    }, 0);
                } else {
                    // 其他一般错误
                    showError(errorMsg);
                }
            }
        } catch (error) {
            console.error('任务状态轮询失败:', error);
            
            // 检查错误消息是否包含特定文本
            const errorMsg = error.message || '获取任务状态失败';
            
            // 针对不同类型的错误显示不同的提示
            if (errorMsg.includes('后台处理服务暂时不可用') || 
                errorMsg.includes('服务不可用') || 
                error.status === 503) {
                // 显示友好的服务不可用提示
                
                // 显示友好的等待提示
                resultArea.classList.remove('hidden');
                resultArea.className = 'mt-4 p-4 bg-yellow-50 border border-yellow-200 rounded-lg';
                resultArea.innerHTML = `
                    <div class="flex items-center justify-between mb-3">
                        <div class="flex items-center">
                            <div class="flex-shrink-0">
                                <i class="fas fa-exclamation-circle text-yellow-500 text-2xl"></i>
                            </div>
                            <div class="ml-3">
                                <h3 class="text-lg font-medium text-yellow-800">处理服务暂时不可用</h3>
                                <p class="text-sm text-yellow-600">${errorMsg}</p>
                            </div>
                        </div>
                        <button type="button" id="closeBusyMessageBtn" class="text-gray-400 hover:text-gray-600 p-1">
                            <i class="fas fa-times"></i>
                        </button>
                    </div>
                    <div class="text-center">
                        <button type="button" id="retryButton" class="mt-2 px-4 py-2 bg-yellow-200 hover:bg-yellow-300 text-yellow-800 rounded-md text-sm font-medium transition duration-200">
                            重新尝试
                        </button>
                    </div>
                `;
                
                // 添加关闭按钮的点击事件 - 使用setTimeout确保DOM已经渲染完成后再绑定事件
                setTimeout(() => {
                    const closeBtn = document.getElementById('closeBusyMessageBtn');
                    if (closeBtn) {
                        closeBtn.onclick = function() {
                            resultArea.classList.add('hidden');
                        };
                    }
                    
                    // 添加重试按钮的点击事件
                    const retryBtn = document.getElementById('retryButton');
                    if (retryBtn) {
                        retryBtn.onclick = function() {
                            // 重置处理状态
                            resultArea.classList.add('hidden');
                            // 重新启动合并过程
                            startMerge();
                        };
                    }
                }, 0);
            } else {
                // 其他一般错误
                showError(errorMsg);
            }
        }
    }
    
    /**
     * 更新进度显示
     */
    function updateProgress(progress) {
        // 更新主进度条
        if (progressBar) {
            progressBar.style.width = `${progress}%`;
            // 添加动画效果
            if (progress < 100) {
                progressBar.classList.add('animate-pulse');
            } else {
                progressBar.classList.remove('animate-pulse');
            }
        }
        
        if (progressText) {
            progressText.textContent = `${progress}%`;
        }
        
        // 更新进度描述
        let statusText = '准备中...';
        let statusClass = 'text-gray-600';
        let logMessage = '';
        let stageIndex = 1;
        
        if (progress > 0 && progress < 30) {
            statusText = '正在读取文件...';
            statusClass = 'text-blue-600';
            logMessage = '正在读取并解析文件内容...';
            stageIndex = 1;
        } else if (progress >= 30 && progress < 60) {
            statusText = '正在合并文档...';
            statusClass = 'text-blue-600';
            logMessage = '正在合并试卷和答案内容...';
            stageIndex = 2;
        } else if (progress >= 60 && progress < 90) {
            statusText = '正在生成最终文件...';
            statusClass = 'text-blue-600';
            logMessage = '正在生成最终的合并文档...';
            stageIndex = 3;
        } else if (progress >= 90 && progress < 100) {
            statusText = '即将完成...';
            statusClass = 'text-green-600';
            logMessage = '正在完成最后的处理...';
            stageIndex = 4;
        } else if (progress === 100) {
            statusText = '处理完成！';
            statusClass = 'text-green-600';
            logMessage = '文档处理完成，准备下载...';
            stageIndex = 4;
        }
        
        const statusElement = document.getElementById('progressStatus');
        if (statusElement) {
            statusElement.textContent = statusText;
            statusElement.className = `text-sm ${statusClass} text-center font-medium`;
        }
        
        // 添加进度图标
        const progressIcon = document.getElementById('progressIcon');
        if (progressIcon) {
            if (progress < 100) {
                progressIcon.className = 'fas fa-spinner fa-spin text-blue-600 text-xl';
            } else {
                progressIcon.className = 'fas fa-check-circle text-green-600 text-xl';
            }
        }
        
        // 添加处理日志
        if (logMessage) {
            addProcessLog(logMessage);
        }
        
        // 更新浮动进度条
        updateFloatingProgress(progress, statusText, stageIndex);
    }
    
    /**
     * 更新浮动进度条
     */
    function updateFloatingProgress(percent, statusMsg, stageIndex) {
        const floatingProgressBar = document.getElementById('floatingProgressBar');
        const floatingProgressText = document.getElementById('floatingProgressText');
        const floatingStatusText = document.getElementById('floatingStatusText');
        const floatingProgress = document.getElementById('floatingProgress');
        const stagePills = document.querySelectorAll('.stage-pill');
        
        // 调试日志
        console.log('更新浮动进度条:', { percent, statusMsg, stageIndex });
        
        if (floatingProgress) {
            // 显示浮动进度条
            if (percent > 0) {
                floatingProgress.style.display = 'block';
                setTimeout(() => {
                    floatingProgress.classList.add('visible');
                }, 10);
            }
            
            // 更新进度条内容
            if (floatingProgressBar) {
                floatingProgressBar.style.width = `${percent}%`;
            }
            
            if (floatingProgressText) {
                floatingProgressText.textContent = `${percent}%`;
            }
            
            if (floatingStatusText && statusMsg) {
                floatingStatusText.textContent = statusMsg;
            }
            
            // 更新阶段指示器
            if (stageIndex && stagePills && stagePills.length) {
                stagePills.forEach(pill => {
                    const pillStage = parseInt(pill.getAttribute('data-stage'));
                    pill.classList.remove('active', 'completed');
                    
                    if (pillStage < stageIndex) {
                        pill.classList.add('completed');
                    } else if (pillStage === stageIndex) {
                        pill.classList.add('active');
                    }
                });
            }
            
            // 当进度到达100%时，自动隐藏浮动进度条
            if (percent >= 100) {
                setTimeout(() => {
                    floatingProgress.classList.remove('visible');
                    setTimeout(() => {
                        floatingProgress.style.display = 'none';
                    }, 300);
                }, 1500);
            }
        }
    }
    
    /**
     * 添加处理日志
     */
    function addProcessLog(message) {
        const processLog = document.getElementById('processLog');
        if (processLog) {
            const logEntry = document.createElement('p');
            logEntry.className = 'log-entry';
            logEntry.textContent = message;
            processLog.querySelector('div').appendChild(logEntry);
            // 自动滚动到底部
            processLog.scrollTop = processLog.scrollHeight;
        }
    }
    
    /**
     * 显示结果
     */
    function showResult(success) {
        if (resultArea) {
            resultArea.classList.remove('hidden');
            // 更新结果区域的样式
            resultArea.className = 'mt-4 p-4 bg-green-50 border border-green-200 rounded-lg';
            resultArea.innerHTML = `
                <div class="flex items-center justify-between">
                    <div class="flex items-center space-x-3">
                        <i class="fas fa-check-circle text-green-500 text-2xl"></i>
                        <div>
                            <h3 class="text-lg font-medium text-green-800">文档合并成功</h3>
                            <p class="text-sm text-green-600">正在准备下载...</p>
                        </div>
                    </div>
                </div>
            `;
        }
    }
    
    /**
     * 显示加载状态
     */
    function showLoading(show) {
        if (show) {
            loadingOverlay.classList.remove('hidden');
            resultArea.classList.add('hidden');
        } else {
            loadingOverlay.classList.add('hidden');
        }
    }
    
    /**
     * 显示错误信息
     */
    function showError(message) {
        errorMessage.textContent = message;
        errorModal.classList.remove('hidden');
    }
    
    /**
     * 工具函数
     */
    function getFileIcon(filename) {
        const ext = filename.split('.').pop().toLowerCase();
        return ext === 'pdf' ? 'fa-file-pdf' : 'fa-file-word';
    }
    
    function formatFileSize(bytes) {
        if (bytes === 0) return '0 B';
        const k = 1024;
        const sizes = ['B', 'KB', 'MB', 'GB'];
        const i = Math.floor(Math.log(bytes) / Math.log(k));
        return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
    }
    
    /**
     * 下载合并后的文档
     */
    async function downloadMergedDocument() {
        try {
            if (!currentTaskId || currentTaskId === 'null') {
                throw new Error('任务ID无效，请重新上传文件');
            }
            
            try {
                await Api.downloadMergedDocument(currentTaskId);
                
                // 确保浮动进度条显示100%后隐藏
                updateProgress(100);
                
                // 显示下载成功信息
                resultArea.classList.remove('hidden');
                resultArea.className = 'mt-4 p-4 bg-green-50 border border-green-200 rounded-lg';
                resultArea.innerHTML = `
                    <div class="flex items-center justify-between">
                        <div class="flex items-center space-x-3">
                            <i class="fas fa-check-circle text-green-500 text-2xl"></i>
                            <div>
                                <h3 class="text-lg font-medium text-green-800">文档合并成功</h3>
                                <p class="text-sm text-green-600">下载已开始，如未自动下载，请检查浏览器下载设置</p>
                            </div>
                        </div>
                    </div>
                `;
            } catch (downloadError) {
                console.error('下载文件失败:', downloadError);
                
                // 检查错误消息是否包含特定文本
                const errorMsg = downloadError.message || '下载失败，请重试';
                
                // 针对不同类型的错误显示不同的提示
                if (errorMsg.includes('后台处理服务暂时不可用') || 
                    errorMsg.includes('服务不可用') || 
                    downloadError.status === 503) {
                    // 显示友好的服务不可用提示
                    
                    // 显示友好的等待提示
                    resultArea.classList.remove('hidden');
                    resultArea.className = 'mt-4 p-4 bg-yellow-50 border border-yellow-200 rounded-lg';
                    resultArea.innerHTML = `
                        <div class="flex items-center justify-between mb-3">
                            <div class="flex items-center">
                                <div class="flex-shrink-0">
                                    <i class="fas fa-exclamation-circle text-yellow-500 text-2xl"></i>
                                </div>
                                <div class="ml-3">
                                    <h3 class="text-lg font-medium text-yellow-800">下载服务暂时不可用</h3>
                                    <p class="text-sm text-yellow-600">${errorMsg}</p>
                                </div>
                            </div>
                            <button type="button" id="closeDownloadErrorBtn" class="text-gray-400 hover:text-gray-600 p-1">
                                <i class="fas fa-times"></i>
                            </button>
                        </div>
                        <div class="text-center">
                            <button type="button" id="retryDownloadButton" class="mt-2 px-4 py-2 bg-yellow-200 hover:bg-yellow-300 text-yellow-800 rounded-md text-sm font-medium transition duration-200">
                                重新下载
                            </button>
                        </div>
                    `;
                    
                    // 添加关闭按钮的点击事件 - 使用setTimeout确保DOM已经渲染完成后再绑定事件
                    setTimeout(() => {
                        const closeBtn = document.getElementById('closeDownloadErrorBtn');
                        if (closeBtn) {
                            closeBtn.onclick = function() {
                                // 重置处理状态
                                resultArea.classList.add('hidden');
                            };
                        }
                        
                        // 添加重试按钮的点击事件
                        const retryBtn = document.getElementById('retryDownloadButton');
                        if (retryBtn) {
                            retryBtn.onclick = function() {
                                // 重置处理状态
                                resultArea.classList.add('hidden');
                                // 重新下载
                                downloadMergedDocument();
                            };
                        }
                    }, 0);
                } else {
                    // 显示一般错误
                    showError(errorMsg);
                    progressArea.classList.add('hidden');
                }
            }
        } catch (error) {
            console.error('下载失败:', error);
            showError(error.message || '下载失败，请重试');
            progressArea.classList.add('hidden');
        }
    }
});

// 全局函数，用于删除文件
function removeFile(type) {
    if (type === 'exam') {
        examFile = null;
        examFileList.innerHTML = '';
    } else {
        answerFile = null;
        answerFileList.innerHTML = '';
    }
    updateMergeButtonState();
} 